<script setup lang="ts">
import {computed} from 'vue';
import {Button} from 'ant-design-vue';
import {BasicIcon} from '#/components/shadcn-ui';
import {useModal} from '#/ui-kit';
import {preferences} from '#/preferences';
import CropperModal from './cropper-modal.vue';

const emits = defineEmits(['update:value']);

const props = defineProps({
  value: {
    type: String,
    default: '',
  },
});

const [Modal, modalApi] = useModal({
  title: '头像上传',
  class: 'w-[800px] min-h-[490px]',
  connectedComponent: CropperModal,
});

const avatar = computed(() => {
  if (props?.value) {
    return props?.value
  } else {
    return preferences.app.defaultAvatar;
  }
});

const handleClick = () => {
  modalApi.setData({avatar: avatar.value})
  modalApi.open();
}

const handleUpdate = (val) => {
  emits('update:value', val);
}
</script>

<template>
  <div class="cropper-avatar">
    <div class="cropper-avatar-wrapper" @click="handleClick">
      <div class="cropper-avatar-mask">
        <div class="cropper-avatar-mask-icon">
          <BasicIcon class="h-[75px] w-[75px]" icon="ant-design:cloud-upload-outlined" color="rgb(214, 214, 214)"/>
        </div>
      </div>
      <img :src="avatar" v-if="avatar" alt="avatar"/>
    </div>

    <Button @click="handleClick" class="mt-3">
      <template #icon>
        <BasicIcon icon="ant-design:cloud-upload-outlined"/>
      </template>
      更换头像
    </Button>

    <Modal @update="handleUpdate"/>
  </div>
</template>

<style scoped lang="scss">
.cropper-avatar {
  display: inline-block;
  text-align: center;
  width: 150px;

  .cropper-avatar-wrapper {
    overflow: hidden;
    border-radius: 50%;
    background: #fff;
    cursor: pointer;
    width: 150px;
    height: 150px;

    .cropper-avatar-mask {
      position: absolute;
      transition: opacity .4s;
      border: inherit;
      border-radius: inherit;
      opacity: 0;
      background: #0006;
      cursor: pointer;
      width: 150px;
      height: 150px;

      .cropper-avatar-mask-icon {
        display: inline-flex;
        width: 150px;
        height: 150px;

        ::v-deep(svg) {
          margin: auto;
        }
      }
    }

    .cropper-avatar-mask:hover {
      opacity: 4000%;
    }
  }
}
</style>